//
//  PresentSimpleAnimator.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/3.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PresentSimpleAnimator.h"

@interface PresentSimpleAnimator ()

@end

@implementation PresentSimpleAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return .3f;
}

- (void)presentTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    // 1. fromVc.view 和 toVc.view 已经实例化，并且已经走完了viewDidLoad.
    // 2. toVc.view还没有加入到containerView当中。
    
    UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    [containerView addSubview:toVC.view];
    
    CGRect toVcFinalRect = [transitionContext finalFrameForViewController:toVC];
    toVC.view.frame = CGRectOffset(toVcFinalRect, CGRectGetWidth(toVcFinalRect), 0);
    
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVc.view.transform = CGAffineTransformMakeScale(.9f, .9f);
        toVC.view.frame = toVcFinalRect;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

- (void)dismissTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *containerView = [transitionContext containerView];
    [containerView insertSubview:toVC.view atIndex:0];
    
    
    
    CGRect fromVcFinalRect = [transitionContext finalFrameForViewController:fromVc];
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVc.view.frame = CGRectOffset(fromVcFinalRect, CGRectGetWidth(fromVcFinalRect), 0);
        toVC.view.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        NSLog(@"finish - %zd", finished);
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}


- (void)dealloc {
    
    NSLog(@"\n************\n %@ dealloc \n************", self.class);
}
@end
